<?php

namespace home\models;

use libs\Utils;
use Yii;
use yii\helpers\Json;

/**
 * This is the model class for table "{{%cart}}".
 *
 * @property string $id 购物车 ID
 * @property string $user_id 用户 ID
 * @property string $product_id 产品 ID
 * @property string $quantity 数量
 * @property string $data 数据
 * @property array $format_data 数据
 *
 * @property Products $product
 */
class Cart extends \common\models\Cart
{

    public $format_data;

    public function afterFind()
    {
        parent::afterFind();

        $this->format_data = Json::decode($this->data);
    }

    public function getProduct()
    {
        return $this->hasOne(Products::className(), ['id' => 'product_id']);
    }

    public function showAttrs()
    {
        $return = [];
        $attrGroup = $this->product->getAttrGroup();
        $attrGroup['size'] = '尺寸';
        foreach($this->format_data as $name => $value){
            $return[] = $attrGroup[$name] . "：" . $value;
        }

        return join("<br />", $return);
    }

    public static function getCount()
    {
        return intval(self::find()->where(['user_id' => Yii::$app->user->id])->sum('quantity'));
    }

    public static function removeAll($ids)
    {
        self::deleteAll(['id' => $ids, 'user_id' => Yii::$app->user->id]);
    }

    /**
     * 生成唯一订单号
     *
     * @param string $time
     *
     * @return string
     */
    public static function genId($time = '')
    {
        if(!$time){
            $time = time();
        }

        $id = sprintf("%02d%02d%d%02d%05d", date("y", $time) + date("N", $time), date("W", $time) + date("N", $time), date("N", $time), date("H", $time) + date("i", $time), Utils::getRand(5, true));

        if(self::find()->where(['id' => $id])->exists()){
            $id = self::genId();
        }

        return $id;
    }
}
